package com.fridge.fridgeList;

import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.fridge.data.DBHelper;
import com.fridge.data.FridgeItem;
import com.fridge.data.ShoppingItem;
import com.fridge.ui.MainActivity;
import com.fridge.util.AlarmNotification;
import com.google.zxing.integration.android.IntentIntegrator;
import com.id2216.fridge.R;

public class FridgeFragment extends Fragment
{
	
    public static final int LISTVIEW_STATUS_NORMAL = 0;
    public static final int LISTVIEW_STATUS_EDIT = 1;

	
    private List<FridgeItem> fridgeItemList; 
    private Button newFridgeItemButton;
    private FridgeAdapter fridgeAdapter;     
	private DBHelper db;
	
	private int listViewEditableStatus;
    
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) { 
        return inflater.inflate(R.layout.fridge_fragment, container, false); 
    } 
       
       
    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
        super.onActivityCreated(savedInstanceState); 

        listViewEditableStatus = View.INVISIBLE;
        setHasOptionsMenu(true);
        
        // Setting Button
       
        
        newFridgeItemButton = (Button) getActivity().findViewById(R.id.newFridgeItem);
        newFridgeItemButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	

//    			IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
//    			scanIntegrator.initiateScan();

        		Intent addNewItemIntent = new Intent();
        		addNewItemIntent.setClass(getActivity().getBaseContext(), AddFridgeItemActivity.class);
        		getActivity().startActivity(addNewItemIntent);

            }
        });
        
        // setup database
        
        db = new DBHelper(getActivity().getApplicationContext());
        fridgeItemList = db.getAllFridgeItem();
        
        fridgeAdapter = new FridgeAdapter(getActivity(),
                R.layout.fridge_item_cell, fridgeItemList);
        
        // table
        
        ListView listView = (ListView) getActivity().findViewById(R.id.fridgeListView); 
        listView.setAdapter(fridgeAdapter); 
        listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) 
			{
				final FridgeItem item = fridgeItemList.get(position);
				if(item.getUiStatus() == View.VISIBLE)
				{
	                // Setting Dialog
					AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
					 
	                alertDialog.setTitle("Delete item ...");	 
	                alertDialog.setMessage("Do you want to delete this item ?");
	                alertDialog.setNegativeButton("NO", null);	 
	                alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int which) {
	                    	if(db.deleteFridgeItem(item) > 0 )
	                    	{
		                    	fridgeItemList.remove(position);
		                    	fridgeAdapter.notifyDataSetChanged();
		                    	Toast.makeText(getActivity().getApplicationContext(), "Item removed from the list", Toast.LENGTH_SHORT).show();	                    		                    		
	                    	}

	                    }
	                });

	                // Showing Alert Message
	                alertDialog.show();

				}
				else
				{
										
					Date date = new Date();
					if( item.getExpire().before(date))
					{
		                // Setting Dialog
						AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
						 
		                alertDialog.setTitle("Expired item");	 
		                alertDialog.setMessage("Do you want to remove expired item ?");
		 
		                alertDialog.setNeutralButton("YES", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int which) {
		                    	if(db.deleteFridgeItem(item) > 0 )
		                    	{
			                    	fridgeItemList.remove(position);
			                    	fridgeAdapter.notifyDataSetChanged();
			                    	Toast.makeText(getActivity().getApplicationContext(), "Item removed from the list", Toast.LENGTH_SHORT).show();	                    	
		                    	}
		                    }
		                });
		 
		                alertDialog.setNegativeButton("MOVE TO SHOPPING LIST", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int which) {
		                    	if(db.moveFridgeItemToShopping(item, false) > 0)
		                    	{
			                    	fridgeItemList.remove(position);
			                    	fridgeAdapter.notifyDataSetChanged();
				                    Toast.makeText(getActivity().getApplicationContext(), "Item moved to the shopping list", Toast.LENGTH_SHORT).show();	                    		
		                    	}
		                    }
		                });
		 
		                alertDialog.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int which) {
		                    	
		                    }
		                });

		
		 
		                // Showing Alert Message
		                alertDialog.show();
					}
					
				}
			}


        	
        })  ; 
        
        
    	setAlarm();
           
    } 
    
    public void toggleListViewEditable()
    {
    	if( listViewEditableStatus == View.INVISIBLE)
    	{
    		listViewEditableStatus = View.VISIBLE;
    		int count = fridgeItemList.size();
    		for (int i = 0; i < count ; i++)
    		{
    			FridgeItem item = fridgeItemList.get(i);
    			item.setUiStatus(View.VISIBLE);
    			
    		}
    		
    	}
    	else
    	{
    		listViewEditableStatus = View.INVISIBLE;
    		int count = fridgeItemList.size();
    		for (int i = 0; i < count ; i++)
    		{
    			FridgeItem item = fridgeItemList.get(i);
    			item.setUiStatus(View.INVISIBLE);
    		}
    		
    	}
    	
    	fridgeAdapter.notifyDataSetChanged();
    }
    
    @Override
    public void onResume() {
        super.onResume();  
        Runnable run = new Runnable(){
            public void run(){
                fridgeItemList.clear();
                List<FridgeItem> allItem = db.getAllFridgeItem();        
                fridgeItemList.addAll(allItem);
                
                fridgeAdapter.notifyDataSetChanged();        
            }            
       };       
       getActivity().runOnUiThread(run);

    
    }
    
    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser == true && fridgeItemList != null) 
        { 
            Runnable run = new Runnable(){
                public void run(){
                	fridgeItemList.clear();
                    List<FridgeItem> allItem = db.getAllFridgeItem();        
                    fridgeItemList.addAll(allItem);
                    
                    fridgeAdapter.notifyDataSetChanged();        
                }            
           };       
           getActivity().runOnUiThread(run);
        }
    }
    
    private void setAlarm() {
    
        AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getActivity(), AlarmNotification.class);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);        
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),5*60*1000, alarmIntent); 

    
    }
    

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {    	    	
    	    	
        switch (item.getItemId()) {
        case R.id.action_deleteItem:
        	toggleListViewEditable();
        	if( listViewEditableStatus == View.INVISIBLE)
        		item.setTitle("DELETE ITEM");
        	else
        		item.setTitle("DONE");
        break;
        }
        return true;
    }
       
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fridge, menu);
        super.onCreateOptionsMenu(menu,inflater);
    }

}
